window.onload = function () {
    //1.1 点击去注册 登录盒子隐藏 注册盒子显示
    $('#loginBox a').on('click',function (){
        $('#loginBox').hide()
        $('#resBOX').show()
    })
    //1.2 点击去登录 注册盒子隐藏 登录盒子显示
    $('#resBOX a').on('click',function (){
        $('#loginBox').show()
        $('#resBOX').hide()
    })

    // 2. 表单验证
    let form = layui.form
    form.verify({
        username: [
            /^[a-zA-Z0-9]{1,9}$/,
            '用户名必须是1-10位字母和数字'
        ],
        password: [
            /^[\S]{6,15}$/,
            "密码长度必须是6-15位的非空字符串"
        ],
        repassword:function (value) {
            let pwd = $('#resBOX [name="password"]').val()
            if (value != pwd) {
                return '两次输入密码不一致,请重新输入'
            }
        }
    })

    // 3.注册功能发送Ajax
    let layer = layui.layer
    $('#resBOX form').on('submit', function (e) {
        e.preventDefault()
        axios({
            url:'/api/reguser',
            method:'post',
            data:$(this).serialize(),          
        }).then(({data:res})=>{
            if (res.status != 0) {
                return layer.msg(res.message)
            }
            layer.msg(res.message)
            $('#resBOX a').click()
            $('#resBOX form')[0].reset()
        })
    })
   
    //  4. 登录功能
    $('#loginBox form').on('submit', function (e) {
        e.preventDefault()
        axios({
            url:'/api/login',
            method:'post',
            data:$(this).serialize(),  
        }).then(({data:res})=>{      
            if (res.status != 0) {
                return layer.msg(res.message)
            }
            layer.msg(res.message)
            localStorage.setItem('token', res.token)
           
            setTimeout(function(){
                location.href='/index.html'
            },1000)
        })
    })
}
